The blanks a filled in below. Each button must have a unique command, but it could be something other than the ones here.
Add some logic so that
a different action is performed for each button.
An ActionEvent
object contains its button's command.
To get it, use the getActionCommand()
method.
For example, if evt
refers to an ActionEvent
,
then evt.getActionCommand()
returns the command.
Since the command is a string, use equals( String )
to compare the command to another string.
public class TwoButtons extends JFrame implements ActionListener { JButton redButton ; JButton grnButton ; // constructor for TwoButtons public TwoButtons() { redButton = new JButton("Red"); grnButton = new JButton("Green"); getContentPane().setLayout( new FlowLayout() ); getContentPane().add( redButton ); getContentPane().add( grnButton ); // register the buttonDemo frame // (the frame this constructor is making) // as the listener for both Buttons. redButton.addActionListener( this ); grnButton.addActionListener( this ); redButton.setActionCommand( "red" ); grnButton.setActionCommand( "green" ); } public void actionPerformed( ActionEvent evt) { if ( evt.getActionCommand().equals( ________ ) ) getContentPane().setBackground( ____________ ); else getContentPane().setBackground( Color.green ); repaint(); } . . . . . . . . }